{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3c1d7485-de5a-4472-a556-175a9ee89ccc",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pa\n",
    "import matplotlib.pyplot as plt\n",
    "a = np.random.random((9, 3))*2  # 随机生成y\n",
    "print(a)\n",
    "a = np.random.rand(4)\n",
    "print(a)\n",
    "a = np.random.random((9, 3))\n",
    "# 定义一维数组\n",
    "x = np.arange(0, 5, 0.2)\n",
    "y1 = x\n",
    "y2 = x**2\n",
    "y3 = x**3\n",
    "# 使用plot绘制线条\n",
    "linesList = plt.plot(x, y1, 'r*-', x, y2, 'r^-', x, y3, 'r.-')\n",
    "# 用setp方法可以同时设置多个线条的属性\n",
    "plt.setp(linesList, color='r')\n",
    "plt.show()\n",
    "plt.plot((x))\n",
    "print(x)\n",
    "plt.show()\n",
    "print('返回的数据类型', type(linesList))\n",
    "print('数据大小：', len(linesList))\n",
    "print(\"s\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bafeb052-5c77-43a5-8347-99e82f096894",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 首先创建一个函数和一个Python3.x的新式类\n",
    "class Demo(object):\n",
    "    def __init__(self):\n",
    "        print(\"Demo Class\")\n",
    "# 定义一个函数\n",
    "def function():\n",
    "    print(\"function hahaha\")\n",
    "# 在Python无论是函数，还是类，都是对象，他们可以赋值给一个变量\n",
    "class_value = Demo\n",
    "func_value = function\n",
    "# 并且可以通过变量调用\n",
    "class_value()   # Demo Class\n",
    "func_value()    # function\n",
    "#Step.2\n",
    "# 将函数和类添加到集合中\n",
    "obj_list = []\n",
    "obj_list.append(class_value)\n",
    "obj_list.append(func_value)\n",
    "# 遍历列表\n",
    "for i,v in enumerate(obj_list):\n",
    "    print(i, v)\n",
    "    if i == 1:\n",
    "        v()\n",
    "    # <class '__main__.Demo'>\n",
    "    # <function function at 0x0000020D681B3E18>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6cf85447",
   "metadata": {},
   "outputs": [],
   "source": [
    "# object是谁实例化的？\n",
    "print(type(object))      # <class 'type'>\n",
    "# object继承自哪个类？\n",
    "print(object.__bases__)  # ()\n",
    "# type是谁实例化的？\n",
    "print(type(type))        # <class 'type'>\n",
    "# type继承自哪个类？\n",
    "print(type.__bases__)    # (<class 'object'>,)\n",
    "# 定义一个变量\n",
    "value = 100\n",
    "# 100由谁实例化？\n",
    "print(type(value))       # <class 'int'>\n",
    "# int由谁实例化？\n",
    "print(type(int))         # <class 'type'>\n",
    "# int继承自哪个类？\n",
    "print(int.__bases__)     # (<class 'object'>,)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d473506a",
   "metadata": {},
   "outputs": [],
   "source": [
    "# instance compare type\n",
    "class A(object):\n",
    "    pass\n",
    "class B(A):\n",
    "    pass\n",
    "b = B()\n",
    "print(isinstance(b, B))\n",
    "print(isinstance(A, A))\n",
    "print(type(b) is B)\n",
    "print(type(b) is A)\n",
    "\n",
    "# True\n",
    "# True\n",
    "# True\n",
    "# False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "84f5e823",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 此处的类也是模板对象，Python中一切皆对象\n",
    "class A(object):\n",
    "    number = 12#类变量\n",
    "    def __init__(self):\n",
    "        # 实例变量 \n",
    "        self.number_2 = 13\n",
    "# 实例变量只能通过类的实例进行调用\n",
    "print(A.number)      # 12\n",
    "print(A().number)    # 12\n",
    "A.number = [1000,1232,43254,345,35322]\n",
    "print(A().number_2)  # 13\n",
    "print(A().number_2)  # 12\n",
    "print(\"A instance\", A().number, A.number) \n",
    "# 修改模板对象创建的对象的属性，模板对象的属性不会改变\n",
    "a = A()\n",
    "a.number = 18\n",
    "print(a.number)      # 18\n",
    "print(A().number)    # 12\n",
    "print(A.number)      # 12\n",
    "# 修改模板对象的属性，由模板对象创建的对象的属性会改变\n",
    "A.number = 19\n",
    "print(A.number)      # 19\n",
    "print(A().number)    # 19\n",
    "\n",
    "a = A()\n",
    "print(a.number, a.number_2)\n",
    "a.number = 124\n",
    "print(a.number, a.number_2)\n",
    "A.number = 19\n",
    "print(a.number, a.number_2)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a89bcfd4",
   "metadata": {},
   "outputs": [],
   "source": [
    "class Demo(object):\n",
    "    #class_insatnce\n",
    "    num = []\n",
    "    # 类方法\n",
    "    @classmethod\n",
    "    def class_method(cls, number):\n",
    "        pass\n",
    "    # 静态方法\n",
    "    @staticmethod\n",
    "    def static_method(number):\n",
    "        pass\n",
    "    # 对象方法/实例方法\n",
    "    def object_method(self, number):\n",
    "        pass\n",
    "print(Demo.object_method(1222,23323))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "791eb8ff",
   "metadata": {},
   "outputs": [],
   "source": [
    "class Home(object):\n",
    "    # 房间中人数\n",
    "    __number = 0\n",
    "    @classmethod\n",
    "    def add_person_number(cls):\n",
    "        cls.__number += 1\n",
    "    @classmethod\n",
    "    def get_person_number(cls):\n",
    "        return cls.__number\n",
    "    def __new__(self):\n",
    "        Home.add_person_number()\n",
    "        # 重写__new__方法，调用object的__new__\n",
    "        return super().__new__(self)\n",
    "class Person(Home):\n",
    "    def __init__(self):\n",
    "        # 房间人员姓名\n",
    "        self.name = 'name'\n",
    "    # 创建人员对象时调用Home的__new__()方法\n",
    "tom = Person()\n",
    "print(type(tom))   # <class '__main__.Person'>\n",
    "alice = Person()\n",
    "bob = Person()\n",
    "test = Person()\n",
    "print(Home.get_person_number())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4a7a1da3",
   "metadata": {},
   "outputs": [],
   "source": [
    "class person(object):\n",
    "    tall = 180\n",
    "    hobbies = [12334,123452]\n",
    "    def __init__(self, name, age,weight):\n",
    "        self.name = name\n",
    "        self.age = age\n",
    "        self.weight = weight\n",
    "    def infoma(self):\n",
    "        print('%s is %s weights %s'%(self.name,self.age,self.weight))\n",
    "Bruce = person(\"Bruce\", 25,180)\n",
    "Bruce.infoma()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5b5e4819",
   "metadata": {},
   "outputs": [],
   "source": [
    "class person(object):\n",
    "    tall = 180\n",
    "    hobbies = [213,234,123432,123432,2345,324,234]\n",
    "    def __init__(self, name, age,weight):\n",
    "        self.name = name\n",
    "        self.age = age\n",
    "        self.weight = weight\n",
    "    @classmethod     #类的装饰器\n",
    "    def infoma(cls):   #cls表示类本身，使用类参数cls\n",
    "        print(cls.__name__)\n",
    "        print(dir(cls))\n",
    "        print(cls.tall, cls.hobbies)\n",
    "#cls表示类本身\n",
    "#person.infoma()  直接调用类的装饰器函数，通过cls可以访问类的相关属性\n",
    "Bruce = person(\"Bruce\", 25,180)   #也可以通过两步骤来实现，第一步实例化person，第二步调用装饰器\n",
    "Bruce.infoma() "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b0f80ab1",
   "metadata": {},
   "outputs": [],
   "source": [
    "class person(object):\n",
    "    tall = 180\n",
    "    hobbies = [21324,1,3,53452]\n",
    "    def __init__(self, name, age,weight):\n",
    "        self.name = name\n",
    "        self.age = age\n",
    "        self.weight = weight\n",
    "    @staticmethod    #静态方法装饰器\n",
    "    def infoma():    #没有参数限制，既不要实例参数，也不用类参数\n",
    "        print(person.tall)\n",
    "        print(person.hobbies)\n",
    "person.infoma()     #静态法可以通过类名访问\n",
    "Bruce = person(\"Bruce\", 25,180)   #通过实例访问\n",
    "Bruce.infoma() "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7d382051",
   "metadata": {},
   "outputs": [],
   "source": [
    "class Parent(object):\n",
    "    numList = []\n",
    "    def numdiff(self, a, b):\n",
    "        return a-b\n",
    "class Child(Parent):\n",
    "    pass\n",
    "c = Child()      \n",
    "Child.numList.extend(range(10))\n",
    "print(Child.numList)\n",
    "print(\"child class\", c.numList)\n",
    "print(\"77 - 2 =\", c.numdiff(77, 2))\n",
    "print(issubclass(Child, Parent))\n",
    "print(issubclass(Child, object))\n",
    "# __bases__ can show all the parent classes\n",
    "#bases属性查看父类\n",
    "print('the bases are:',Child.__bases__)\n",
    "# doc string will not be inherited\n",
    "#doc属性不会被继承\n",
    "print(Parent.__doc__)\n",
    "print(Child.__doc__)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7d1e51ca",
   "metadata": {},
   "outputs": [],
   "source": [
    "# inherit\n",
    "#定义父类：Parent\n",
    "class Parent(object):\n",
    "    def __init__(self, name):\n",
    "        self.name = name\n",
    "        print(\"create an instance of:\", self.__class__.__name__)\n",
    "        print(\"name attribute is:\", self.name)\n",
    "#定义子类Child ，继承父类Parent       \n",
    "class Child(Parent):\n",
    "    def __init__(self,st):\n",
    "        self.names = st\n",
    "        print(\"create an instance of:\", self.__class__.__name__)\n",
    "        print(\"name attribute is init child:\", self.names)\n",
    "        super(Child,self).__init__(\"data from Child\")\n",
    "#子类实例化时，由于子类没有初始化，此时父类的初始化函数就会默认被调用\n",
    "#且必须传入父类的参数name\n",
    "c = Child(\"init Child\")\n",
    "print(c.name, c.names)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ce5bd4f4",
   "metadata": {},
   "outputs": [],
   "source": [
    "# inherit function\n",
    "class Parent(object):\n",
    "    Value = \"Hi, Parent value\"\n",
    "    def fun(self):\n",
    "        print(\"This is from Parent\")\n",
    "\n",
    "class Child(Parent):\n",
    "    Value = \"Hi, Child  value\"\n",
    "    def fun(self):\n",
    "        print(\"This is from Child\")\n",
    "        #Parent.fun(self)\n",
    "        super(Child,self).fun()  #相当于用super的方法与上一调用父类的语句置换\n",
    "\n",
    "c = Child()    \n",
    "c.fun()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b0beec6e",
   "metadata": {},
   "outputs": [],
   "source": [
    "'''\n",
    "\"__“和” _ __\"的使用 更多的是一种规范/约定，并没有真正达到限制的目的：\n",
    "“_”：以单下划线开头的表示的是protected类型的变量，即只能允许其本身与子类进行访问；同时表示弱内部变量标示，如，当使用\"from moduleNmae import *\"时，不会将以一个下划线开头的对象引入。\n",
    "“__”：双下划线的表示的是私有类型的变量。只能是允许这个类本身进行访问了，连子类也不可以，这类属性在运行时属性名会加上单下划线和类名。\n",
    "'''\n",
    "try:\n",
    "    fh = open(\"testfile\", \"w\")\n",
    "    fh.write(\"这是一个测试文件，用于测试异常!!\")\n",
    "except IOError:\n",
    "    print \"Error: 没有找到文件或读取文件失败\"\n",
    "else:\n",
    "    print \"内容写入文件成功\"\n",
    "    fh.close()\n",
    "    \n",
    "    \n",
    "try:\n",
    "    fh = open(\"testfile\", \"w\")\n",
    "    try:\n",
    "        fh.write(\"这是一个测试文件，用于测试异常!!\")\n",
    "    finally:\n",
    "        print \"关闭文件\"\n",
    "        fh.close()\n",
    "except IOError:\n",
    "    print \"Error: 没有找到文件或读取文件失败\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "91425ddc",
   "metadata": {},
   "outputs": [],
   "source": [
    "# map可以用于对可遍历结构的每个元素执行同样的操作，批量操作：\n",
    "map(lambda x: x**2, [1, 2, 3, 4])                 # [1, 4, 9, 16]\n",
    "map(lambda x, y: x + y, [1, 2, 3], [5, 6, 7])     # [6, 8, 10]\n",
    "# 在Python3种输出上述结果\n",
    "result1=list(map(lambda x: x**2, [1, 2, 3, 4]) )                # [1, 4, 9, 16]\n",
    "print(result1)\n",
    "result2 = (map(lambda x, y: x + y, [1, 2, 3], [5, 6, 7]))     # [6, 8, 10]\n",
    "print(result2)\n",
    "# reduce则是对可遍历结构的元素按顺序进行两个输入参数的操作\n",
    "# 并且每次的结果保存作为下次操作的第一个输入参数，还没有遍历的元素作为第二个输入参数\n",
    "# 这样的结果就是把一串可遍历的值，减少（reduce）成一个对象\n",
    "from functools import reduce\n",
    "res=reduce(lambda x, y: x + y, [1, 2, 3, 4])    # ((1+2)+3)+4=10\n",
    "print(res)\n",
    "# filter顾名思义，根据条件对可遍历结构进行筛选\n",
    "filter(lambda x: x % 2, [1, 2, 3, 4, 5])    # 筛选奇数，[1, 3, 5]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "326cba74",
   "metadata": {},
   "outputs": [],
   "source": [
    "# thread\n",
    "import time, threading\n",
    "# 新线程执行的代码:\n",
    "def loop():\n",
    "    print('thread %s is running...' % threading.current_thread().name)\n",
    "    n = 0\n",
    "    while n < 5:\n",
    "        n = n + 1\n",
    "        print('thread %s >>> %s' % (threading.current_thread().name, n))\n",
    "        time.sleep(1)\n",
    "    print('thread %s ended.' % threading.current_thread().name)\n",
    "\n",
    "print('thread %s is running...' % threading.current_thread().name)\n",
    "t = threading.Thread(target=loop, name='LoopThread')\n",
    "t.start()\n",
    "t.join()\n",
    "print('thread %s ended.' % threading.current_thread().name)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a2ba0a40",
   "metadata": {},
   "outputs": [],
   "source": [
    "from urllib import request\n",
    "with request.urlopen('https://www.baidu.com') as f:\n",
    "    data = f.read()\n",
    "    print('Status:', f.status, f.reason)\n",
    "    for k, v in f.getheaders():\n",
    "        print('%s: %s' % (k, v))\n",
    "    print('Data:', data.decode('utf-8'))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "33aa3867",
   "metadata": {},
   "outputs": [],
   "source": [
    "import psutil\n",
    "psutil.cpu_count()  # CPU逻辑数量\n",
    "psutil.cpu_count(logical=False)  # CPU物理核心\n",
    "#psutil.test()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "649a2309",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 导入SQLite驱动:\n",
    "import sqlite3\n",
    "# 连接到SQLite数据库\n",
    "# 数据库文件是test.db\n",
    "# 如果文件不存在，会自动在当前目录创建:\n",
    "conn = sqlite3.connect('test.db')\n",
    "# 创建一个Cursor:\n",
    "cursor = conn.cursor()\n",
    "# 执行一条SQL语句，创建user表:\n",
    "cursor.execute('create table user (id varchar(20) primary key, name varchar(20))')\n",
    "#<sqlite3.Cursor object at 0x10f8aa260>\n",
    "# 继续执行一条SQL语句，插入一条记录:\n",
    "cursor.execute('insert into user (id, name) values (\\'1\\', \\'Michael\\')')\n",
    "#<sqlite3.Cursor object at 0x10f8aa260>\n",
    "# 通过rowcount获得插入的行数:\n",
    "print(\"insert line : \",cursor.rowcount)\n",
    "# 关闭Cursor:\n",
    "cursor.close()\n",
    "# 提交事务:\n",
    "conn.commit()\n",
    "# 关闭Connection:\n",
    "conn.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c1f851b6",
   "metadata": {},
   "outputs": [],
   "source": [
    "conn = sqlite3.connect('test.db')\n",
    "cursor = conn.cursor()\n",
    "# 执行查询语句:\n",
    "cursor.execute('select * from user where id=?', ('1',))\n",
    "#<sqlite3.Cursor object at 0x10f8aa340>\n",
    "# 获得查询结果集:\n",
    "values = cursor.fetchall()\n",
    "print(\"get result : \", values, type(values))\n",
    "cursor.close()\n",
    "conn.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7a8a767c",
   "metadata": {},
   "outputs": [],
   "source": [
    "from __future__ import print_function\n",
    "import torch\n",
    "import numpy\n",
    "x = torch.Tensor(5, 3)\n",
    "print(x, type(x))\n",
    "y = numpy.random.ranf((5, 3))\n",
    "print(y, type(y), numpy.shape(y))\n",
    "x = torch.rand(5, 3)\n",
    "print(x, type(x), x.size())\n",
    "a = torch.rand(5, 3)\n",
    "b = torch.Tensor(5, 3)\n",
    "print(a, type(a), b, type(b))\n",
    "c = torch.add(a, b)\n",
    "print(a, type(a), b, type(b),c, type(c))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5225759e",
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "x = torch.rand(2, 2)\n",
    "y = torch.rand(2, 2)\n",
    "print(x, \"x\")\n",
    "print(y, \"y\")\n",
    "print(x + y)\n",
    "print(torch.add(x, y))\n",
    "x += y\n",
    "print(x)\n",
    "print(x[1, :], \"qq\")\n",
    "x = torch.rand(4, 4)\n",
    "print(x, x.size(), x.dtype)\n",
    "y = x.view(2, 8)\n",
    "print(y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "f4139f6a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([[0, 0, 0],\n",
      "        [0, 0, 0],\n",
      "        [0, 0, 0],\n",
      "        [0, 0, 0],\n",
      "        [0, 0, 0]])\n",
      "torch.Size([5, 3])\n",
      "torch.int64\n",
      "[3124234, 123421] tensor([3124234.,  123421.]) <class 'list'> <class 'torch.Tensor'>\n",
      "tensor([0.5253, 0.2487])\n",
      "tensor([0.2487])\n"
     ]
    }
   ],
   "source": [
    "import torch\n",
    "x = torch.zeros(5, 3, dtype=torch.long)\n",
    "print(x)\n",
    "print(x.size())\n",
    "print(x.dtype)\n",
    "l = [3124234,123421]\n",
    "x = torch.Tensor(l)\n",
    "print(l, x, type(l), type(x))\n",
    "x = torch.rand_like(x, dtype=torch.float)\n",
    "print(x)\n",
    "print(x[1:])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "27a5b863",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([1., 1., 1., 1., 1.]) <class 'torch.Tensor'>\n",
      "[1. 1. 1. 1. 1.] <class 'numpy.ndarray'>\n",
      "[1. 1. 1. 1. 1.] <class 'numpy.ndarray'>\n",
      "[2. 2. 2. 2. 2.] <class 'numpy.ndarray'>\n",
      "tensor([2., 2., 2., 2., 2.], dtype=torch.float64) <class 'torch.Tensor'>\n",
      "no surrport cuda\n"
     ]
    }
   ],
   "source": [
    "import numpy \n",
    "import torch\n",
    "a = torch.ones(5)\n",
    "print(a, type(a))\n",
    "b = a.numpy() # torch to numpy (tensor -> ndarray)\n",
    "print(b, type(b))\n",
    "a = numpy.ones(5)\n",
    "print(a, type(a))\n",
    "b = torch.from_numpy(a)\n",
    "numpy.add(a, 1, out=a)\n",
    "print(a ,type(a))\n",
    "print(b, type(b))\n",
    "if torch.cuda.is_available():\n",
    "    device = torch.device(\"cuda\")          # a CUDA device object\n",
    "    y = torch.ones_like(x, device=device)  # 直接在GPU上创建tensor\n",
    "    x = x.to(device)                       # 或者使用`.to(\"cuda\")`方法\n",
    "    z = x + y\n",
    "    print(z)\n",
    "    print(z.to(\"cpu\", torch.double))       # `.to`也能在移动时改变dtyp\n",
    "else:\n",
    "    print(\"no surrport cuda\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "15f5ce52",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "输出的结果：\n",
      "tensor([1., 2., 3.])\n",
      "tensor([1, 2, 3], dtype=torch.int32)\n",
      "tensor([1, 2, 3], dtype=torch.int32)\n",
      "tensor([1, 2, 3], dtype=torch.int32)\n",
      "输出的类型：\n",
      "torch.float32\n",
      "torch.int32\n",
      "torch.int32\n",
      "torch.int32\n",
      "torch.float32\n"
     ]
    }
   ],
   "source": [
    "import torch\n",
    "import numpy as np\n",
    "data = np.array([1, 2, 3])\n",
    "\n",
    "Tensor = torch.Tensor(data)\n",
    "tensor = torch.tensor(data)\n",
    "from_numpy = torch.from_numpy(data)\n",
    "as_tensor = torch.as_tensor(data)\n",
    "print('输出的结果：')\n",
    "print(Tensor)\n",
    "print(tensor)\n",
    "print(from_numpy)\n",
    "print(as_tensor)\n",
    "\n",
    "print('输出的类型：')\n",
    "print(Tensor.dtype)\n",
    "print(tensor.dtype)\n",
    "print(from_numpy.dtype)\n",
    "print(as_tensor.dtype)\n",
    "print(torch.get_default_dtype())\n",
    "# from_numpy as_tensor 浅拷贝， 推荐使用 as_tensor，可以接受 python 原生 list\n",
    "# tensor Tensor 深拷贝"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9149c137",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "id": "d9107c48",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[ 12 334]\n",
      " [223  33]] <class 'numpy.ndarray'> int32\n",
      "tensor([[ 12., 334.],\n",
      "        [223.,  33.]], dtype=torch.float64, requires_grad=True) <class 'torch.Tensor'> torch.float64\n",
      "tensor([[ 44., 366.],\n",
      "        [255.,  65.]], dtype=torch.float64, grad_fn=<AddBackward0>) <class 'torch.Tensor'> torch.float64\n",
      "tensor([[ 88.0432, 732.4445],\n",
      "        [510.6843, 130.1294]], dtype=torch.float64, grad_fn=<AddBackward0>) <class 'torch.Tensor'> torch.float64\n",
      "<AddBackward0 object at 0x000002A33CD38A90>\n"
     ]
    }
   ],
   "source": [
    "import torch\n",
    "import numpy as np\n",
    "a = numpy.array([[12,334],[223,33]])\n",
    "print(a, type(a), a.dtype)\n",
    "b = torch.tensor(a, dtype=torch.float64, requires_grad=True)\n",
    "print(b, type(b), b.dtype)\n",
    "b = b + 32\n",
    "print(b, type(b), b.dtype)\n",
    "b = b * 2\n",
    "b = b + torch.rand(2,2)\n",
    "print(b, type(b), b.dtype) #numpy 默认 int32, tensor float32\n",
    "print(b.grad_fn)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "id": "c8b4a46b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "False\n",
      "True\n",
      "<SumBackward0 object at 0x000002A33BB59160>\n",
      "None\n",
      "tensor([-0.1271,  1.0101, -0.2528], requires_grad=True) x\n",
      "tensor([-0.2542,  2.0203, -0.5057], grad_fn=<MulBackward0>) y\n",
      "tensor([-130.1741, 1034.3812, -258.9066], grad_fn=<MulBackward0>)\n"
     ]
    }
   ],
   "source": [
    "import torch\n",
    "a = torch.randn(2, 2)\n",
    "a = ((a * 3) / (a - 1))\n",
    "print(a.requires_grad)\n",
    "a.requires_grad_(True)\n",
    "print(a.requires_grad)\n",
    "b = (a * a).sum()\n",
    "print(b.grad_fn)\n",
    "print(b.backward())\n",
    "\n",
    "x = torch.randn(3, requires_grad=True)\n",
    "print(x, \"x\")\n",
    "y = x * 2\n",
    "print(y, \"y\")\n",
    "while y.data.norm() < 1000:\n",
    "    y = y * 2\n",
    "\n",
    "print(y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "id": "c1edf05e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([[ 0.6655,  0.4265,  1.7196,  0.3186],\n",
      "        [ 0.7267, -1.2127, -1.2932,  2.1082]])\n",
      "tensor([[-1.5206,  3.1096, -1.7555],\n",
      "        [ 2.1242, -1.6728,  2.6895]], grad_fn=<AddBackward0>)\n"
     ]
    }
   ],
   "source": [
    "import torch as t\n",
    "from torch import nn\n",
    "class Linear(nn.Module): # 继承nn.Module\n",
    "    def __init__(self, in_features, out_features):\n",
    "        super(Linear, self).__init__() # 等价于nn.Module.__init__(self)\n",
    "        self.w = nn.Parameter(t.randn(in_features, out_features))\n",
    "        self.b = nn.Parameter(t.randn(out_features))\n",
    "    \n",
    "    def forward(self, x):\n",
    "        x = x.mm(self.w) # x.@(self.w)\n",
    "        return x + self.b.expand_as(x)\n",
    "layer = Linear(4, 3)\n",
    "print(\"in, out\", t.randn(4,3))\n",
    "print(\"out\", t.randn(3))\n",
    "input = t.randn(2,4)\n",
    "print(input)\n",
    "output = layer(input)\n",
    "print(output)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d75a2311",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  },
  "widgets": {
   "application/vnd.jupyter.widget-state+json": {
    "state": {},
    "version_major": 2,
    "version_minor": 0
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
